import React, { useEffect, useState } from 'react'
import Header from '../components/Header'
import SearchModule from './DataManagement/SearchModule'
import UploadModule from './DataManagement/UploadModule'
import BrowseModule from './DataManagement/BrowseModule'
// 🔧 修改：使用真实的 API，而不是 mockApi
import { getDataStatistics } from '../utils/api'
import '../styles/theme.css'
import '../styles/backgrounds.css'
import './DataManagement.css'

export default function DataManagement() {
  const [currentView, setCurrentView] = useState('dashboard') // 'dashboard', 'upload', 'search', 'browse'
  const [stats, setStats] = useState({ 
    total: 0, 
    tags: {}, 
    defectCount: 0, 
    normalCount: 0,
    aiProcessedCount: 0,
    avgConfidence: 0
  })

  useEffect(() => { 
    updateStats()
  }, [])

  async function updateStats() {
    try {
      const statsData = await getDataStatistics()
      setStats({
        total: statsData.total || 0,
        tags: statsData.tagCounts || {},
        defectCount: statsData.defectCount || 0,
        normalCount: statsData.normalCount || 0,
        aiProcessedCount: statsData.aiProcessedCount || 0,
        avgConfidence: statsData.avgConfidence || 0
      })
    } catch (err) {
      console.error('统计信息更新失败', err)
    }
  }

  // 功能模块配置
  const modules = [
    {
      id: 'upload',
      title: '智能上传',
      subtitle: 'AI 自动检测与分析',
      icon: '📤',
      description: '上传叶片图片，AI 自动识别缺陷类型，生成标签和描述',
      features: ['AI 缺陷检测', '自动标签生成', '智能描述', '向量化存储'],
      color: 'from-blue-500 to-cyan-500'
    },
    {
      id: 'search',
      title: '智能搜索',
      subtitle: '多模态搜索引擎',
      icon: '🔍',
      description: '支持文本搜索、图片相似性搜索和语义搜索',
      features: ['文本搜索', '相似图片搜索', '语义搜索', '高级筛选'],
      color: 'from-green-500 to-emerald-500'
    },
    {
      id: 'browse',
      title: '数据浏览',
      subtitle: '图片库管理',
      icon: '🗂️',
      description: '浏览所有图片数据，支持分类查看和批量操作',
      features: ['分类浏览', '批量操作', '详情查看', '数据导出'],
      color: 'from-purple-500 to-violet-500'
    }
  ]

  // 渲染功能卡片
  const renderFunctionCard = (module) => (
    <div 
      key={module.id}
      className="function-card"
      onClick={() => setCurrentView(module.id)}
    >
      <div className="function-icon">
        <span>{module.icon}</span>
      </div>
      <div className="function-content">
        <h3 className="function-title">{module.title}</h3>
        <p className="function-subtitle">{module.subtitle}</p>
        <p className="function-description">{module.description}</p>
        <div className="function-features">
          {module.features.map((feature, index) => (
            <span key={index} className="feature-tag">
              {feature}
            </span>
          ))}
        </div>
      </div>
      <div className="function-arrow">
        <span>→</span>
      </div>
    </div>
  )

  // 渲染主仪表板
  const renderDashboard = () => (
    <>
      {/* 页面标题 */}
      <div className="page-header">
        <div>
          <h2 className="page-title">数据管理中心</h2>
        </div>
      </div>

      {/* 统计概览区 */}
      <div className="stats-overview">
        <div className="stat-card">
          <div className="stat-icon">📊</div>
          <div className="stat-content">
            <span className="stat-value">{stats.total}</span>
            <span className="stat-label">总图片数</span>
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-icon">⚠️</div>
          <div className="stat-content">
            <span className="stat-value">{stats.defectCount}</span>
            <span className="stat-label">缺陷图片</span>
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-icon">✅</div>
          <div className="stat-content">
            <span className="stat-value">{stats.normalCount}</span>
            <span className="stat-label">正常图片</span>
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-icon">🏷️</div>
          <div className="stat-content">
            <span className="stat-value">{Object.keys(stats.tags).length}</span>
            <span className="stat-label">缺陷类型</span>
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-icon">🤖</div>
          <div className="stat-content">
            <span className="stat-value">{stats.aiProcessedCount}</span>
            <span className="stat-label">AI 处理</span>
          </div>
        </div>
      </div>

      {/* 功能模块卡片 */}
      <div className="card">
        <div className="card-header">
          <div className="section-title">
            <span className="section-icon">🛠️</span>
            <div>
              <h3 className="card-title">功能模块</h3>
              <p className="card-subtitle">选择下方功能模块进入对应页面</p>
            </div>
          </div>
        </div>
        <div className="functions-grid">
          {modules.map(renderFunctionCard)}
        </div>
      </div>

      {/* 快速操作区 */}
      <div className="card">
        <div className="card-header">
          <div className="section-title">
            <span className="section-icon">⚡</span>
            <div>
              <h3 className="card-title">快速操作</h3>
              <p className="card-subtitle">常用功能快捷入口</p>
            </div>
          </div>
        </div>
        <div className="quick-actions">
          <button 
            className="quick-action-btn"
            onClick={() => setCurrentView('upload')}
          >
            <span className="action-icon">📤</span>
            <span>智能上传</span>
          </button>
          <button 
            className="quick-action-btn"
            onClick={() => setCurrentView('search')}
          >
            <span className="action-icon">🔍</span>
            <span>智能搜索</span>
          </button>
          <button 
            className="quick-action-btn"
            onClick={() => setCurrentView('browse')}
          >
            <span className="action-icon">🗂️</span>
            <span>数据浏览</span>
          </button>
        </div>
      </div>
    </>
  )

  return (
    <div className="data-management-page">
      <div className="site-bg bg-core" aria-hidden="true" />

      <div className="page-bg">
        <Header />
        <div className="container page">
          {/* 面包屑导航 */}
          {currentView !== 'dashboard' && (
            <div className="breadcrumb">
              <button 
                className="breadcrumb-btn"
                onClick={() => setCurrentView('dashboard')}
              >
                <span>🏠</span>
                <span>数据管理中心</span>
              </button>
              <span className="breadcrumb-separator">→</span>
              <span className="breadcrumb-current">
                {modules.find(m => m.id === currentView)?.title || '未知页面'}
              </span>
            </div>
          )}

          {/* 根据当前视图渲染内容 */}
          {currentView === 'dashboard' && renderDashboard()}
          {currentView === 'upload' && (
            <UploadModule 
              onBack={() => setCurrentView('dashboard')}
              onStatsUpdate={updateStats}
            />
          )}
          {currentView === 'search' && (
            <SearchModule 
              onBack={() => setCurrentView('dashboard')}
              stats={stats}
            />
          )}
          {currentView === 'browse' && (
            <BrowseModule 
              onBack={() => setCurrentView('dashboard')}
              stats={stats}
            />
          )}
        </div>
      </div>
    </div>
  )
}